package cn.tp.ksoft.civil_driver.view.widget;

import android.content.Context;
import android.database.DataSetObserver;
import android.util.AttributeSet;
import android.util.DisplayMetrics;
import android.util.SparseArray;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
/**
 * @author zhusong@dianhun.com
 * @Date: 2014-12-25 上午11:18:45
 * @Function: 自动换行布局
 */
public class WrapLayout extends ViewGroup implements OnClickListener{
	
	private BaseAdapter mAdapter;
	
	private DataSetObserver mDataSetObserver;
	
	private SparseArray<View> mScrapView;
	
	private SparseArray<RowInfo> rows;
	
	private OnWrapListener listener;

	private final int DEFAULT_DIVER_SPACE_H = 10;
	private final int DEFAULT_DIVER_SPACE_V = 5;
	private int mDiverHSpace;
	private int mDiverVSpace;
	public WrapLayout(Context context, AttributeSet attrs, int defStyle) {
		super(context, attrs, defStyle);
		init();
	}

	public WrapLayout(Context context, AttributeSet attrs) {
		super(context, attrs);
		init();
	}

	public WrapLayout(Context context) {
		super(context);
		init();
	}

	private void init() {
		rows = new SparseArray<RowInfo>();
		mScrapView = new SparseArray<View>();
		DisplayMetrics dm = getResources().getDisplayMetrics();
		mDiverHSpace = Math.round(DEFAULT_DIVER_SPACE_H * dm.density);
		mDiverVSpace = Math.round(DEFAULT_DIVER_SPACE_V * dm.density);
	}
	/**
	 * 设置适配器
	 * @param adapter
	 */
	public void setAdapter(BaseAdapter adapter) {
		if(null != mAdapter && mDataSetObserver != null) {
			mAdapter.unregisterDataSetObserver(mDataSetObserver);
		}
		
		mAdapter = adapter;
		if(null != mAdapter) {
			mDataSetObserver = new DataSetObserver() {
				// 通知数据更改时重新添加子视图
				@Override
				public void onChanged() {
					removeAllViews();
					for (int i = 0, length = mAdapter.getCount(); i < length; i++) {
						View child = mAdapter.getView(i, mScrapView.get(i), null);
						addViewFixed(child);
						child.setOnClickListener(WrapLayout.this);
						mScrapView.append(i, child);
					}
					
				}
			};
			mAdapter.registerDataSetObserver(mDataSetObserver);
			mAdapter.notifyDataSetChanged();
		} else {
			removeAllViews();
		}
	}
	/**
	 * 调整过的添加视图方法
	 * @param child
	 */
	private void addViewFixed(View child) {
		if(null == child) {
			return;
		}
		ViewGroup parent = (ViewGroup) child.getParent();
		if(null != parent) {
			parent.removeView(child);
		}
		addView(child);
	}
	/**
	 * 设置监听
	 * @param listener
	 */
	public void setOnWrapListener(OnWrapListener listener) {
		this.listener = listener;
	} 
	
	/**
	 * 计算换行与高度
	 */
	@Override
	protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
		final int widthSize = MeasureSpec.getSize(widthMeasureSpec) - getPaddingLeft() - getPaddingRight() + mDiverHSpace;
		int lineMaxHeight = 0;
		
		int lineWidthRecord = 0;
		RowInfo rowInfo = new RowInfo();
		int line = 0;
		// 遍历子视图,计算换行
		for (int i = 0,length = getChildCount(); i < length; i++) {
			View child = getChildAt(i);
			measureChild(child, widthMeasureSpec, heightMeasureSpec);
			lineWidthRecord += child.getMeasuredWidth() + mDiverHSpace;
			// 当前子视图应当换行
			if(lineWidthRecord >= widthSize) {
				rowInfo.setLineHeight(lineMaxHeight);
				rows.append(line, rowInfo);
				line++;
				rowInfo = new RowInfo();
				lineWidthRecord = child.getMeasuredWidth();
				lineMaxHeight = 0;
			}
			
			if(child.getMeasuredHeight() > lineMaxHeight) {
				lineMaxHeight = child.getMeasuredHeight();
			}
			rowInfo.addRowView(child);
		}
		
		if(rowInfo.size() > 0) {
			rowInfo.setLineHeight(lineMaxHeight);
			rows.append(line, rowInfo);
		}
		
		// 布局高度
		int heightSize = getPaddingTop() + getPaddingBottom();
		for (int i = 0,length = rows.size(); i < length; i++) {
			RowInfo row = rows.get(i);
			heightSize += row.getLineHeight();
			if (i != length-1) {
				heightSize += mDiverVSpace;
			}
		}
		setMeasuredDimension(widthSize, heightSize);
	}
	
	@Override
	protected void onLayout(boolean changed, int l, int t, int r, int b) {
		// 放置行视图位置
		int top = getPaddingTop();
		int left = getPaddingLeft();
		for (int i = 0,length = rows.size(); i < length; i++) {
			RowInfo row = rows.get(i);
			SparseArray<View> rowViews = row.getRowViews();
			for (int j = 0, count = rowViews.size(); j < count; j++) {
				View child = rowViews.get(j);
				child.layout(left, top, left+child.getMeasuredWidth(), top + child.getMeasuredHeight());
				left += child.getMeasuredWidth() + mDiverHSpace;
			}
			
			top += row.getLineHeight() + mDiverVSpace;
			left = getPaddingLeft();
		}
	}

	@Override
	public void onClick(View v) {
		if(null != listener) {
			int index = indexOfChild(v);
			listener.onWrapItemClick(index);
		}
	}
	/**
	 * @author zhusong@dianhun.com
	 * @Date: 2014-12-25 上午9:47:06
	 * @Function: 行信息
	 */
	class RowInfo {
		private int lineHeight;
		private SparseArray<View> rowViews;
		int index = 0;
		
		public void addRowView(View view) {
			if(null == rowViews) {
				rowViews = new SparseArray<View>();
			}
			rowViews.append(index, view);
			index++;
		}

		public int size() {
			return null == rowViews ? 0 : rowViews.size();
		}
		public int getLineHeight() {
			return lineHeight;
		}

		public void setLineHeight(int lineHeight) {
			this.lineHeight = lineHeight;
		}

		public SparseArray<View> getRowViews() {
			return rowViews;
		}
	}
	
	
	public interface OnWrapListener {
		public void onWrapItemClick(int position);
	}
}
